package com.example.webchar.webchar.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 邮箱工具类
 *
 * @program: wechat-web-is-my
 * @description
 * @author: 郭逍
 * @create: 2021/8/28 22:48
 **/
@Slf4j
@Component
public class MailUtils {
    @Autowired
    private JavaMailSenderImpl mailSender;

    /**
     * 发送者
     */
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 简单邮件
     *
     * @param to
     * @param subject
     * @param text
     * @throws MessagingException
     */
    public void sendMail(String to, String subject, String text) throws MessagingException {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);
        mailSender.send(simpleMailMessage);
        log.info("send to {} ; {} ; {} ;", to, subject, text);
    }

    /**
     * 复杂邮件
     *
     * @param to
     * @param subject
     * @param text
     * @param inlineName
     * @param inlineFilePath
     * @param attachmentName
     * @param attachmentPath
     * @throws MessagingException
     */
    public void sendMail(String to, String subject, String text, String inlineName, String inlineFilePath, String attachmentName, String attachmentPath) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom(from);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(text);
        messageHelper.addInline(inlineName, new File(inlineFilePath));
        messageHelper.addAttachment(attachmentName, new File(attachmentPath));
        mailSender.send(mimeMessage);
    }

    public String generatedcode(int count) {

        String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, count - 1)));
        return code;
    }
}
